package com.elderly.utils;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description 手机号验证码和封禁处理
 * @Date 2021/10/7 8:41
 * @Created 30500
 */
@Component
public class PhoneUtils {
    /**
     * redis 的使用工具类
     */
    @Resource
    private RedisUtils redisUtils;

    /**
     * 验证码的存储时间
     */
    private static final Integer EXPIRE_CODE_TIME = 5 * 60;

    /**
     * 手机号封禁时间
     */
    private static final Integer EXPIRE_BAN_PHONE_TIME = 60 * 60;

    /**
     * 手机号封禁
     */
    public static final Integer CHOOSE_PHONE_BAN = 1;

    /**
     * 手机验证码登录次数
     */
    public static final Integer CHOOSE_PHONE_COUNT = 2;


    /**
     * @return boolean
     * @description 验证码过期时间
     * @author 30500
     * @date 2021/10/5 16:51
     * @type [java.lang.String 键,
     *        java.lang.String 值]
     */
    public boolean setCode(String key, String value) {
        return redisUtils.set(key, value, EXPIRE_CODE_TIME);
    }

    /**
     * @description 获取手机验证码
     * @author 30500
     * @date 2021/10/7 8:49
     * @type [java.lang.String]
     * @return java.lang.String
     */
    public String getCode(String key) {
        String s = redisUtils.get(key);
        return s;
    }

    /**
     * @description 手机号封禁, 验证码错误次数
     * @author 30500
     * @date 2021/10/7 9:14
     * @type [java.lang.String 手机号,
     *        int 状态]
     * @return boolean
     */
    public boolean setPhone(String phone, int status) {
        if (status == CHOOSE_PHONE_BAN)
            return redisUtils.set(phone + "ban", "ban", EXPIRE_BAN_PHONE_TIME);
        else if (status == CHOOSE_PHONE_COUNT) {
            String s = redisUtils.get(phone + "count");
            if (s == null) return redisUtils.set(phone + "count", String.valueOf(1), EXPIRE_BAN_PHONE_TIME);
            else {
                return redisUtils.increase(phone + "count");
            }
        }
        return false;
    }

    /**
     * @description 取出手机号的相关设定值
     * @author 30500
     * @date 2021/10/7 9:20
     * @type [java.lang.String 手机号,
     *        int 状态]
     * @return java.lang.String
     */
    public String getPhone(String phone, int status) {
        String result = null;
        if (status == CHOOSE_PHONE_BAN)
            result = redisUtils.get(phone + "ban");
        else if (status == CHOOSE_PHONE_COUNT)
            result = redisUtils.get(phone + "count");
        return result;
    }

    /**
     * @description 删除登录验证码计数
     * @author 30500
     * @date 2021/10/7 9:34
     * @type [java.lang.String 手机号]
     * @return boolean
     */
    public boolean delPhone(String phone) {
        return redisUtils.del(phone + "count");
    }
}
